<template>
  <div class="fmainBox">
    <!-- <div class="ncweacher">
      <farm-weacher @change="getItem" />
    </div> -->
    <div class="tqyb">
      <el-tabs
        v-model="activeName"
        @tab-click="onTabChange"
        type="card"
        class="demo-tabs">
        <!-- 天气预报 -->
        <el-tab-pane label="天气预报" name="prediction" >
          <template v-if="userStore.userInfo.farmId">

            <today-weather-info ref="twiRef"></today-weather-info>

            <div class="wtitle"> <span>72小时天气</span></div>
            <weather72hour ref="w72h"></weather72hour>

            <div class="wtitle"> <span>15日预报</span></div>
            <weather15day ref="w15d"></weather15day>

          </template>
          <template v-else>
            <div style="text-align: center;padding:50px 0; font-size:14px">暂无数据</div>
          </template>
        </el-tab-pane>
        <!-- 历史天气 -->
        <el-tab-pane label="历史天气" name="history">
          <el-row>
            <el-col :span="6">
              <el-radio-group v-model="activeHistoryName" @change="changeHistory">
                <el-radio-button label="temp">有效积温</el-radio-button>
                <el-radio-button label="rainfall">降雨量</el-radio-button>
              </el-radio-group>
            </el-col>
            <el-col :span="18" style="display:flex;align-items:center;justify-content: end;">
              <span>时间范围：</span>
              <el-date-picker
                v-model="dateRanges"
                type="daterange"
                range-separator="至"
                start-placeholder="选择开始时间"
                end-placeholder="选择结束时间"
                @change="changeRange"
              />
              <span style="margin-left:30px;margin-right:10px;" v-show="activeHistoryName=='temp'">生物学零度</span>
              <el-input-number v-model="tempNum" :min="-100" :max="100" @change="tempChange" v-show="activeHistoryName=='temp'"/>
              <span style="margin-left:10px;" v-show="activeHistoryName=='temp'">℃</span>
              <!-- <el-icon style="margin-left:15px;" size="24px" color="#999" @click="downloadData"><Download /></el-icon> -->
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7">
              <div class="humidity-statistics" v-if="activeHistoryName=='temp'">
                <div class="ico" :style="'background-image:url(https://ftp.cqtancheng.com/files/farming-skin/icon-humidity.png)'"></div>
                <div style="font-weight: bold;">有效积温{{countAccTemp?countAccTemp:0}}℃</div>
                <div v-if="countAccTemp>=countLastYearAccTemp">比去年同期高{{countAccTemp-countLastYearAccTemp}}℃</div>
                <div v-else>比去年同期低{{countLastYearAccTemp-countAccTemp}}℃</div>
                <div class="up" v-if="countAccTemp>countLastYearAccTemp">↑</div>
                <div class="dn" v-if="countAccTemp==countLastYearAccTemp">-</div>
                <div class="dn" v-if="countAccTemp<countLastYearAccTemp">↓</div>
              </div>
              <div class="humidity-statistics" v-if="activeHistoryName=='rainfall'">
                <div class="ico" :style="'background-image:url(https://ftp.cqtancheng.com/files/farming-skin/icon-rainfall.png)'"></div>
                <div style="font-weight: bold;">平均日降雨量{{(avgRain).toFixed(2)}}mm</div>
                <div v-if="avgRain>=lastYearAvgRain">比去年同期高{{(avgRain-lastYearAvgRain).toFixed(2)}}mm</div>
                <div v-else>比去年同期低{{(lastYearAvgRain-avgRain).toFixed(2)}}mm</div>
                <div class="up" v-if="avgRain>lastYearAvgRain">↑</div>
                <div class="dn" v-if="avgRain==lastYearAvgRain">-</div>
                <div class="dn" v-if="avgRain<lastYearAvgRain">↓</div>
              </div>
            </el-col>
            <template v-if="activeHistoryName=='temp'">
              <el-col :span="24" style="position: relative;">
                <!-- temp 01 -->
                <div class="nodata" v-if="isEmpty">
                  <el-empty description="暂无数据" image-size="128" />
                </div>
                <div class="temp01" id="tempChart01"></div>
              </el-col>
              <el-col :span="24" style="position: relative;" >
                <!-- temp 02 -->
                <div class="nodata" v-if="isEmpty">
                  <el-empty description="暂无数据" image-size="128" />
                </div>
                <div class="temp02" id="tempChart02"></div>
              </el-col>
          </template>
          <template v-if="activeHistoryName=='rainfall'">
            <el-col :span="24" style="position: relative;" >
              <!-- rain 01 -->
              <div class="nodata" v-if="isEmpty">
                <el-empty description="暂无数据" image-size="128" />
              </div>
              <div class="rain" id="rainChart"></div>
            </el-col>
          </template>

            <el-col :span="24">
              <div style="padding:20px;">
                <vxe-table
                border
                show-overflow
                size="small"
                :max-height="400"
                :row-config="{isHover: true}"
                :data="tableList"
                :scroll-y="{enabled: true}">
                <vxe-column field="weatherDay" align="center" title="日期" ></vxe-column>
                <template v-if="activeHistoryName=='temp'">
                    <vxe-column field="temp" align="center" title="日平均温度/℃"></vxe-column>
                    <vxe-column field="accTemp" align="center" title="有效积温/℃">
                      <template #default="{row}">
                        {{row.accTemp!=null?row.accTemp:0}}
                      </template>
                    </vxe-column>
                    <vxe-column field="accTempLastyear" align="center" title="去年历史同期/℃"></vxe-column>
                    <vxe-column field="manyYearTempAvg" align="center" title="多年历史同期/℃">
                      <template #default="{row}">
                          <span style="padding-right:5px">{{row.manyYearTempAvg.toFixed(2)}}</span>
                          <span class="up" v-if="row.accTemp > row.manyYearTempAvg">↑</span>
                          <span class="md" v-if="row.accTemp == row.manyYearTempAvg">-</span>
                          <span class="dn" v-if="row.accTemp < row.manyYearTempAvg">↓</span>
                        </template>
                    </vxe-column>
                  </template>
                  <template v-if="activeHistoryName=='rainfall'">
                      <vxe-column field="precip" align="center" title="降雨量/mm"></vxe-column>
                      <vxe-column field="precipLastyear" align="center" title="去年历史同期/mm"></vxe-column>
                      <vxe-column field="manyYearTempAvg" align="center" title="多年历史同期平均/℃">
                        <template #default="{row}">
                          <span style="padding-right:5px">{{row.manyYearRainfallAvg}}</span>
                            <span class="up" v-if="row.precip > row.manyYearRainfallAvg">↑</span>
                            <span class="md" v-if="row.precip == row.manyYearRainfallAvg">-</span>
                            <span class="dn" v-if="row.precip < row.manyYearRainfallAvg">↓</span>
                          </template>
                      </vxe-column>
                </template>
              </vxe-table>
              </div>
            </el-col>
          </el-row>

        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup name="courseList">
// 这里的name是为了做页面缓存，其值要跟路由里面的name值一样
import { nextTick, ref, watch, onActivated, reactive, onMounted } from 'vue'
import { getCouseList } from '@/api/user'
import { getHistory } from '@/api/weather'
import { useUserStore } from '@/pinia/modules/user'
import { useFramStore } from '@/pinia/modules/farm'
import { message } from '@/utils/element'
import farmWeacher from './components/farmWeacher.vue'
import todayWeather from './components/todayWeather.vue'
import rainAnalysis from './components/rainAnalysis.vue'
import oneDayWeather from './components/oneDayWeather.vue'
import fifteenDayWeacher from './components/fifteenDayWeacher.vue'
import todayWeatherInfo from './components/todayWeatherInfo.vue'
import weather72hour from './components/weather72hour.vue'
import weather15day from './components/weather15day.vue'
import moment from 'moment'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getFarmWeather } from '@/api/plant'

const activeName = ref('prediction')
const activeHistoryName = ref('temp')

const userStore = useUserStore()
const framStore = useFramStore()

const w72h = ref(null)
const w15d = ref(null)
const twiRef = ref(null)
const twRef = ref(null)
const time = ref('')
const startDate = ref(new Date())
const endDate = ref('')
const tempNum = ref(10)
const dateRanges = ref([])

const district = ref('')
const list = ref([])
const tableList = ref([])

const countAccTemp = ref(0)
const countLastYearAccTemp = ref(0)

const avgRain = ref(0)
const lastYearAvgRain = ref(0)

const isEmpty = ref(true)
const weatherItem = ref({}) 

onMounted(async() => {
  dateRanges.value = [moment().subtract(1, 'M').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]

  let currentFarm = userStore.userInfo.farmList.find(item=>item.farmId==userStore.userInfo.farmId)

  if( currentFarm.district && currentFarm.district.length > 2 ){
    let districtText = currentFarm.district.indexOf('区') != -1? currentFarm.district.replaceAll('区', '') : currentFarm.district
    districtText = currentFarm.district.indexOf('县') != -1? currentFarm.district.replaceAll('县', '') : districtText
    district.value = districtText
    getChart()
  }
  twiRef.value.get_Prediction_Weather(`${currentFarm.locationLongitude},${currentFarm.locationLatitude}`)
  w72h.value.get_weather_72_hour(`${currentFarm.locationLongitude},${currentFarm.locationLatitude}`)
  w15d.value.get_weather_15_day(`${currentFarm.locationLongitude},${currentFarm.locationLatitude}`)

})

const setChart = () => {
  console.log('setChart: ', list.value)
  let jnTemp = []
  let qnTemp = []
  let dnTemp = []
  let tempDate = []
  countAccTemp.value = 0
  countLastYearAccTemp.value = 0
  let lt = null
  if( list.value.length > 0 ){
    lt = list.value[list.value.length-1]
  }
  list.value.forEach(t => {
    jnTemp.push(t.accTemp)
    qnTemp.push(t.accTempLastyear)
    dnTemp.push(t.manyYearTempAvg)
    tempDate.push(t.weatherDay)
    // countAccTemp.value += (t.temp - tempNum.value)
    // countLastYearAccTemp.value += (t.tempLastyear - tempNum.value)
    if( t.tempLastyear >= tempNum.value ){
      countLastYearAccTemp.value += t.tempLastyear
    }
  })

  countAccTemp.value = lt.accTemp

  let tempChartDom01 = document.getElementById('tempChart01')
  let tempChart01 = echarts.init(tempChartDom01)
  let tempOption = {
    title: {
      text: '所选时间范围与历史同期有效积温趋势变化图',
      left: 'center',
      top: '7px',
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    color: ['#5174cc', '#e5832c', '#ecba00'],
    grid: {
      left: '55px',
      right: '30px',
      bottom: '50px',
      top: '70px'
    },
    legend: {
      top: '35px',
      data: ['有效积温', '去年历史同期', '多年历史同期']
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: tempDate
    },
    yAxis: {
      type: 'value',
      name: '°C',
      nameTextStyle: {
        padding:[0,30,0,0]
      }
    },
    series: [
      {
        name: '有效积温',
        data: jnTemp,
        symbol: 'circle',
        symbolSize: 6,
        type: 'line'
      },
      {
        name: '去年历史同期',
        data: qnTemp,
        symbol: 'circle',
        symbolSize: 6,
        type: 'line'
      },
      {
        name: '多年历史同期',
        data: dnTemp,
        symbol: 'circle',
        symbolSize: 6,
        type: 'line'
      }
    ]
  }
  if( tempDate.length == 0 ){
    isEmpty.value = true
  }else{
    isEmpty.value = false
  }
  if( list.value.length == 0 ){
    tempOption.yAxis.name = ''
  }
  tempChart01.clear()
  tempChart01.setOption(tempOption)
}

const setChart2 = () => {
  // console.log('setChart2: ', list.value)
  let maxTempList = []
  let minTempList = []
  let tempDate = []
  list.value.forEach(t => {
    tempDate.push(t.weatherDay)
    maxTempList.push(t.tempMax)
    minTempList.push(t.tempMin)
  })

  let tempChartDom02 = document.getElementById('tempChart02')
  let tempChart02 = echarts.init(tempChartDom02)
  let tempOption ={
    title: {
      text: '所选时间范围每日最高、最低温趋势变化图',
      left: 'center',
      top: '7px',
      textStyle: {
        fontSize: 14
      }
    },
    color: ['#e5832c', '#3a4de9'],
    grid: {
      left: '55px',
      right: '30px',
      bottom: '50px',
      top: '70px'
    },
    tooltip: {
      trigger: 'axis'
    },
    // dataZoom: [
    //   {
    //     type: 'inside',
    //     start: 0,
    //     end: 20
    //   },
    //   {
    //     start: 0,
    //     end: 20
    //   }
    // ],
    legend: {
      top: '35px',
      data: ['日最高温', '日最低温']
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: tempDate
    },
    yAxis: {
      type: 'value',
      name: '°C',
      nameTextStyle: {
        padding:[0,30,0,0]
      }
    },
    series: [
      {
        name: '日最高温',
        data: maxTempList,
        type: 'line',
        smooth: .6,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(229,131,44,0.8)'
            },
            {
              offset: 1,
              color: 'rgba(229,131,44,0.3)'
            }
          ])
        },
      },
      {
        name: '日最低温',
        data: minTempList,
        type: 'line',
        smooth: .6,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(58,77,233,0.8)'
            },
            {
              offset: 1,
              color: 'rgba(58,77,233,0.3)'
            }
          ])
        },
      }
    ]
  }
  if( list.value.length == 0 ){
    tempOption.yAxis.name = ''
  }
  tempChart02.clear()
  tempChart02.setOption(tempOption)
}

const setChart3 = () => {
  let jnRain = []
  let qnRain = []
  let dnRain = []
  let tempDate = []

  let avgRainList = []
  let lastYearAvgRainList = []
  let avgRainTotal = 0
  let lastYearAvgRainTotal = 0
  // list.value.forEach(r=>{
  //   avgRainList.push(r.accRainfall)
  //   lastYearAvgRainList.push(r.accRainfallLastyear)
  // })

  list.value.forEach(t => {
    jnRain.push(t.precip)
    qnRain.push(t.precipLastyear)
    dnRain.push(t.manyYearRainfallAvg)
    tempDate.push(t.weatherDay)

    avgRainTotal += t.precip
    lastYearAvgRainTotal += t.precipLastyear
  })

  avgRain.value = avgRainTotal/list.value.length
  lastYearAvgRain.value = lastYearAvgRainTotal/list.value.length

  let rainChartDom = document.getElementById('rainChart')
  let rainChart = echarts.init(rainChartDom)
  let tempOption ={
    title: {
      text: '所选时间范围与历史同期日降雨量趋势变化图',
      left: 'center',
      top: '7px',
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    color: ['#5174cc', '#e5832c', '#ecba00'],
    grid: {
      left: '55px',
      right: '30px',
      bottom: '50px',
      top: '70px'
    },
    legend: {
      top: '35px',
      data: ['降雨量', '去年历史同期', '多年历史同期']
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: tempDate
    },
    yAxis: {
      type: 'value',
      name: 'mm',
      nameTextStyle: {
        padding:[0,30,0,0]
      }
    },
    series: [
      {
        name: '降雨量',
        data: jnRain,
        symbol: 'circle',
        symbolSize: 6,
        smooth: 0.6,
        type: 'line'
      },
      {
        name: '去年历史同期',
        data: qnRain,
        symbol: 'circle',
        symbolSize: 6,
        smooth: 0.6,
        type: 'line'
      },
      {
        name: '多年历史同期',
        data: dnRain,
        symbol: 'circle',
        symbolSize: 6,
        smooth: 0.6,
        type: 'line'
      },
    ]
  }
  if( tempDate.length == 0 ){
    isEmpty.value = true
  }else{
    isEmpty.value = false
  }
  if( list.value.length == 0 ){
    tempOption.yAxis.name = ''
  }
  rainChart.clear()
  rainChart.setOption(tempOption)
}

const getChart = async () => {
  let sds = moment(dateRanges.value[0]).format('YYYY-MM-DD')
  let eds = moment(dateRanges.value[1]).format('YYYY-MM-DD')
  // district, temp, sd, ed
  let data = {
    district: district.value,
    // temp: tempNum.value,
    shengwuxue: tempNum.value,
    weatherDayStart: sds,
    weatherDayEnd: eds
  }
  let res = await getHistory(data)
  if( res.success ){
    // console.log('load: ', res.data)
    list.value = res.data
    tableList.value = res.data.slice()
    tableList.value.reverse()
  }

  if( activeName.value == 'history' ){
    if( activeHistoryName.value == 'temp' ){
      setChart()
      setChart2()
    }
    if( activeHistoryName.value == 'rainfall' ){
      setChart3()
    }
  }

}

const tempChange = (num) => {
  // console.log(num)
  getChart()
}

const changeRange = (d) => {
  console.log(d)
  if( d[0].getFullYear() != d[1].getFullYear() ){
    ElMessage.warning('只能选择同一年的日期范围！')
    let s = new Date()
    let e = new Date()
    s.setMonth(0)
    s.setDate(1)
    dateRanges.value = [s, e]
  }else{
    startDate.value = d[0]
    getChart()
  }
}

const disabledDate = (time) => {
  if( startDate.value ){
    return (
      moment(time).year() > moment(startDate.value).year() ||
      time.getTime() > Date.now()
    )
  }
}

const changeHistory = () => {
  if( activeHistoryName.value == 'temp' ){
    setChart()
    setChart2()
  }
  if( activeHistoryName.value == 'rainfall' ){
    setChart3()
  }
}

const onTabChange = () => {
  if( activeName.value == 'history' ){
    setTimeout(()=>{
      changeHistory()
    },300)
  }
}

</script>

<style lang="scss" scoped>
  .fmainBox{
      display: flex;
      box-sizing: border-box;
      //border: 1px solid red;
      min-width: 1200px;
      .wtitle{
          box-sizing: border-box;
          display: flex;
          height: auto;
          align-items: center;
          border-bottom: 1px solid #ededed;
          padding-bottom: 6px;
          padding:0 10px 10px 10px;
          span{
              display: flex;
              align-items: center;
              font-size: 16px;
              flex: 1;
              font-weight: bold;
              &::before{
                  content: "";
                  display: block;
                  width: 3px;
                  background: #FF9C00;
                  height: 14px;
                  margin: 0 3px 0 0;
              }
          }
      }
      .ncweacher{
          box-sizing: border-box;
          width: 350px;
          background-color: #fff;
          padding: 10px;
          flex-shrink: 0;
      }
      .tqyb{
          flex: 1;
          box-sizing: border-box;
          background-color: #fff;
          margin: 0 0 0 10px;
          padding: 10px;
          width: calc(100vw - 637px);;
      }
  }

  .humidity-statistics {
      box-sizing: border-box;
      display: flex;
      font-size: 14px;
      justify-content: center;
      border: 1px solid #999;
      border-radius: 20px;
      padding: 10px 0;
      gap: 5px;
      align-items: center;
      .ico {
        width: 20px;
        height: 20px;
        background-position: center;
        background-size: cover;
      }
      .up {
        color: #a00; font-weight: bold;
      }
      .dn {
        color: #0c0; font-weight: bold;
      }
    }

    .temp01{
      height: 360px;
    }

    .temp02{
      height: 360px;
    }

    .rain{
      height: 360px;
    }

    .nodata{
      position: absolute; left: 50%; top: 45px; margin-left: -64px;
    }

    .up{color: #a00;}
    .md{color: #ccc}
    .dn{color: #0c0}
</style>
  
